﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class DTgame_Bullet_exploresion : MonoBehaviour
{
    // Start is called before the first frame update
    public float moveSpeed;
    public int explosionDamage;     //中心爆炸范围
    public float explosionRadius;   //爆炸范围
    public float explosionPower;    //爆炸冲击力
    public GameObject exploresionFx;    //爆炸粒子
    public UnityEvent damageEvent;
    // Start is called before the first frame update
    void Start()
    {
        Destroy(gameObject, 5f);
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (damageEvent != null)
        {
            damageEvent.Invoke();
        }

        //if(collision.gameObject.GetComponent<TDgame_TankHP>()!=null)
        //{
        //    collision.gameObject.GetComponent<TDgame_TankHP>().TakeDamage(10);
        //}

        collision.collider.SendMessageUpwards("TakeDamage", 10f, SendMessageOptions.DontRequireReceiver);
        var fx=Instantiate(exploresionFx, transform.position, transform.rotation);
        Destroy(fx, 2f);
        Collider[] hitColliders = Physics.OverlapSphere(transform.position, explosionRadius);
        for (int i = 0; i < hitColliders.Length; i++)
        {
            //计算从爆炸中心到碰撞体表面的距离
            //返回碰撞体与爆炸中心最近的点
            Vector3 closestPoint = hitColliders[i].ClosestPointOnBounds(transform.position);
            //计算距离
            float distance = Vector3.Distance(closestPoint, transform.position);
            //计算伤害点数的百分比，随着距离的增大降低(Clamp01 钳制数值在0~1之间  )
            float hitPointPercentage = 1.0f - Mathf.Clamp01(distance / explosionRadius);
            //计算最后总的伤害点数
            int damage = (int)(hitPointPercentage * explosionDamage);
            //向受到影响的碰撞体发送伤害消息，调用该物体的减血方法
            hitColliders[i].SendMessageUpwards("TakeDamage", damage, SendMessageOptions.DontRequireReceiver);
            //如果碰撞体上有刚体组件，则施加一个爆炸力
            if (hitColliders[i].GetComponent<Rigidbody>() != null)
            {
                hitColliders[i].GetComponent<Rigidbody>().
                    AddExplosionForce(explosionPower,//力度
                                      transform.position,//爆炸中心位置
                                      explosionRadius);//爆炸影响半径
            }

        }
        Destroy(gameObject);
    }
}
